import { apiClient } from './client'
import { ApiResponse } from '@/types/api'

export interface ApiKey {
  id: string
  name: string
  keyPrefix: string
  permissions: string[]
  rateLimitPerHour: number
  lastUsedAt?: string
  lastUsedIp?: string
  expiresAt?: string
  createdAt: string
  updatedAt: string
}

export interface CreateApiKeyRequest {
  name: string
  permissions: string[]
  rateLimitPerHour: number
  expiresAt?: string
}

export interface UpdateApiKeyRequest {
  name?: string
  permissions?: string[]
  rateLimitPerHour?: number
  expiresAt?: string
}

export interface CreateApiKeyResponse {
  apiKey: ApiKey
  secretKey: string
}

export class ApiKeyService {
  // Get all API keys for the current user
  async getApiKeys(): Promise<ApiResponse<{ apiKeys: ApiKey[] }>> {
    return apiClient.get('/keys')
  }

  // Get a specific API key by ID
  async getApiKey(keyId: string): Promise<ApiResponse<{ apiKey: ApiKey }>> {
    return apiClient.get(`/keys/${keyId}`)
  }

  // Create a new API key
  async createApiKey(data: CreateApiKeyRequest): Promise<ApiResponse<CreateApiKeyResponse>> {
    return apiClient.post('/keys', data)
  }

  // Update an existing API key
  async updateApiKey(keyId: string, data: UpdateApiKeyRequest): Promise<ApiResponse<{ apiKey: ApiKey }>> {
    return apiClient.put(`/keys/${keyId}`, data)
  }

  // Delete an API key
  async deleteApiKey(keyId: string): Promise<ApiResponse> {
    return apiClient.delete(`/keys/${keyId}`)
  }

  // Get API key usage statistics
  async getApiKeyUsage(keyId: string, period = '30d'): Promise<ApiResponse<any>> {
    return apiClient.get(`/keys/${keyId}/usage?period=${period}`)
  }

  // Regenerate an API key (creates new secret while keeping same permissions)
  async regenerateApiKey(keyId: string): Promise<ApiResponse<CreateApiKeyResponse>> {
    return apiClient.post(`/keys/${keyId}/regenerate`)
  }

  // Get available permissions
  async getAvailablePermissions(): Promise<ApiResponse<{ permissions: Array<{ value: string; label: string; description: string }> }>> {
    return apiClient.get('/keys/permissions')
  }

  // Test API key validity
  async testApiKey(apiKey: string): Promise<ApiResponse<{ valid: boolean; permissions: string[] }>> {
    return apiClient.post('/keys/test', { apiKey })
  }
}

export const apiKeyService = new ApiKeyService()
